<template>
  <el-cascader v-model="model" :options="departments" @change="handleChange"/>
</template>
<script lang="ts" setup>
import {CascaderNodePathValue, CascaderOption, CascaderValue} from "element-plus";
import {getDepartments} from "@/api/department";
import {ref} from "vue";
import {DepartmentResponse2} from "@/api/types/department";

const props = defineProps<{ type: "departmentId" | "departmentIds" }>()
const model = defineModel<CascaderValue>()
const departments = ref<CascaderOption[]>()
const departmentId = defineModel<number>("departmentId")
const departmentIds = defineModel<number[]>("departmentIds")

async function getData() {
  const {data} = await getDepartments()
  if (data?.info_list !== undefined) {
    departments.value = data.info_list?.map(department => (departmentToCascaderOption(department)))
  }
}

function departmentToCascaderOption(department: DepartmentResponse2): CascaderOption {
  return {
    label: department.dept_name,
    value: department.selfid,
    children: department.childs?.map(department => departmentToCascaderOption(department as DepartmentResponse2))
  }
}

getData()

function handleChange(value: CascaderValue) {
  if (Array.isArray(value)) {
    if (props.type === "departmentId") {
      departmentId.value = Number(value[value.length - 1])
    } else if (props.type === "departmentIds" && value.every(value => Array.isArray(value))) {
      departmentIds.value = (value as CascaderNodePathValue[]).map(arr => Number(arr[arr.length - 1]))
    }
  }
}
</script>
